#include <graphics.h>
#include <easyx.h>
#include <conio.h>
#include <string>

using namespace std;
#pragma warning (disable:4996)
#define height 600
#define width 800
COLORREF color[10];
TCHAR g[100];
int colorn = 0;
int g_len; // Hilbert 曲线的单位长度
TCHAR s[] = _T("迭代阶数");
int level = 1; //初始阶数
bool start = 0;

ExMessage m;
void setbk()
{
	initgraph(width, height); // 设置窗口大小
	rectangle(143, 23, 657, 537); // 绘制表示范围的矩形框
	settextstyle(37, 0, _T("Times"));
	outtextxy(0, 30, s);
	setorigin(144, 24); // 设置原点坐标
}
void setcolor()
{
	color[0] = RGB(125, 0, 0);
	color[1] = RGB(255, 0, 0);
	color[2] = RGB(0, 125, 0);
	color[3] = RGB(0, 255, 0);
	color[4] = RGB(0, 0, 125);
	color[5] = RGB(0, 0, 255);
}
void drawhilbert(string cmd, int a)
{
	BeginBatchDraw();
	static BYTE d = 0; // 方向
	static POINT c[4] = { 1, 0, 0, -1, -1, 0, 0, 1 }; // 方向对应的轴系数
	if (a < 0) return; //终止条件
	int count = 0;
	setlinecolor(color[colorn % 6]); //设定颜色
	while (cmd[count])
	{
		switch (cmd[count++])
		{
		case '+': d = (d + 1) & 3; break;
		case '-': d = (d - 1) & 3; break;
		case 'L': drawhilbert("+RF-LFL-FR+", a - 1); break;
		case 'R': drawhilbert("-LF+RFR+FL-", a - 1); break;
		case 'F': linerel(c[d].x * g_len, c[d].y * g_len); break; //开始划线
		}
	}
}
void input()
{
	m = getmessage(EM_MOUSE);
	if (m.message == WM_MOUSEWHEEL)
	{
		level++;
	}
	else if (m.message == WM_LBUTTONDOWN)
	{
		level--;
	}
	else if (m.message == WM_RBUTTONDOWN)
	{
		start = start ? 0 : 1;
	}
	level = level % 9;
	setorigin(0, 0);
	_stprintf(g, _T("%d"), level);//输出整型数字
	settextstyle(50, 0, _T("Times"));
	settextcolor(RGB(0, 255, 0));
	outtextxy(10, 70, g);
	setorigin(144, 24); // 设置原点坐标
}
void withoutinput()
{
	bar(0, 0, 511, 511); // 清空绘图区
	g_len = 512 >> level; // 计算单位长度
	moveto(g_len / 2, 512 - g_len / 2); // 设定起点
	drawhilbert("L", level); // 递归绘制 Hilbert 曲线
	FlushBatchDraw();
}
int main()
{
	setcolor();
	setbk();
	while (1)
	{
		input();
		if (start) {
			colorn++;
			Sleep(200);
		}
		if (colorn > 1000) colorn = 0;
		withoutinput();
	}
	EndBatchDraw();//结束绘画
	_getch();
	// closegraph();
}